import sys
import os
from PyQt5.QtWidgets import (QApplication, QMainWindow, QWidget, QPushButton, QVBoxLayout,
                             QHBoxLayout, QLabel, QLineEdit, QMessageBox, QStackedWidget,
                             QGroupBox, QFormLayout, QDialog, QTabWidget, QTableWidget,
                             QTableWidgetItem, QHeaderView, QComboBox, QTextEdit, QGridLayout,
                             QSpinBox, QRadioButton, QButtonGroup)
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QFont

# 添加项目根目录到系统路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from database import Database
from iteration6_fee_management.generate_fee import FeeGenerator
from iteration6_fee_management.pay_fee import FeePayment
from iteration6_fee_management.query_fee import FeeQuery

# 费用生成窗口
class GenerateFeeDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('生成费用账单')
        self.setGeometry(300, 300, 400, 300)
        self.generator = FeeGenerator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 获取所有宿舍信息
        db = Database()
        db.connect()
        db.cursor.execute(
            "SELECT id, building, room_number FROM dormitory ORDER BY building, room_number"
        )
        dormitories = db.cursor.fetchall()
        db.close()
        
        # 宿舍选择下拉框
        self.dormitory_combo = QComboBox()
        for dorm in dormitories:
            self.dormitory_combo.addItem(f"{dorm[1]}-{dorm[2]} (ID: {dorm[0]})", dorm[0])
        form_layout.addRow('宿舍:', self.dormitory_combo)
        
        self.fee_type_input = QLineEdit()
        self.fee_type_input.setPlaceholderText('例如: 水费、电费、住宿费')
        form_layout.addRow('费用类型:', self.fee_type_input)
        
        self.amount_input = QLineEdit()
        self.amount_input.setPlaceholderText('例如: 100')
        form_layout.addRow('费用金额:', self.amount_input)
        
        self.due_days_input = QSpinBox()
        self.due_days_input.setRange(1, 365)
        self.due_days_input.setValue(30)
        form_layout.addRow('缴费期限(天):', self.due_days_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('费用信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.generate_button = QPushButton('生成账单')
        self.generate_button.clicked.connect(self.generate_fee)
        button_layout.addWidget(self.generate_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def generate_fee(self):
        dormitory_id = self.dormitory_combo.currentData()
        fee_type = self.fee_type_input.text().strip()
        amount = self.amount_input.text().strip()
        due_days = self.due_days_input.value()
        
        if not fee_type or not amount:
            QMessageBox.warning(self, '警告', '费用类型和金额不能为空')
            return
        
        try:
            amount = float(amount)
            result = self.generator.generate_fee(dormitory_id, fee_type, amount, due_days)
            
            if result:
                QMessageBox.information(self, '成功', '费用账单已生成')
                self.accept()
        except ValueError:
            QMessageBox.warning(self, '警告', '费用金额必须是数字')

# 批量费用生成窗口
class BatchGenerateFeeDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('批量生成费用账单')
        self.setGeometry(300, 300, 400, 300)
        self.generator = FeeGenerator()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.fee_type_input = QLineEdit()
        self.fee_type_input.setPlaceholderText('例如: 水费、电费、住宿费')
        form_layout.addRow('费用类型:', self.fee_type_input)
        
        self.amount_per_person_input = QLineEdit()
        self.amount_per_person_input.setPlaceholderText('例如: 50')
        form_layout.addRow('每人费用金额:', self.amount_per_person_input)
        
        self.due_days_input = QSpinBox()
        self.due_days_input.setRange(1, 365)
        self.due_days_input.setValue(30)
        form_layout.addRow('缴费期限(天):', self.due_days_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('批量费用信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.generate_button = QPushButton('批量生成账单')
        self.generate_button.clicked.connect(self.batch_generate_fee)
        button_layout.addWidget(self.generate_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def batch_generate_fee(self):
        fee_type = self.fee_type_input.text().strip()
        amount_per_person = self.amount_per_person_input.text().strip()
        due_days = self.due_days_input.value()
        
        if not fee_type or not amount_per_person:
            QMessageBox.warning(self, '警告', '费用类型和每人金额不能为空')
            return
        
        try:
            amount_per_person = float(amount_per_person)
            result = self.generator.generate_batch_fee(fee_type, amount_per_person, due_days)
            
            if result:
                QMessageBox.information(self, '成功', '批量费用账单已生成')
                self.accept()
        except ValueError:
            QMessageBox.warning(self, '警告', '每人费用金额必须是数字')

# 费用缴纳窗口
class PayFeeDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('缴纳费用')
        self.setGeometry(300, 300, 400, 200)
        self.payment = FeePayment()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        self.fee_id_input = QLineEdit()
        self.fee_id_input.setPlaceholderText('例如: 1')
        form_layout.addRow('费用记录ID:', self.fee_id_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('缴费信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.pay_button = QPushButton('缴费')
        self.pay_button.clicked.connect(self.pay_fee)
        button_layout.addWidget(self.pay_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def pay_fee(self):
        fee_id = self.fee_id_input.text().strip()
        
        if not fee_id:
            QMessageBox.warning(self, '警告', '费用记录ID不能为空')
            return
        
        try:
            result = self.payment.pay_fee(fee_id)
            
            if result:
                QMessageBox.information(self, '成功', '费用已缴纳')
                self.accept()
        except Exception as e:
            QMessageBox.warning(self, '错误', f'缴费失败: {str(e)}')

# 宿舍费用缴纳窗口
class PayDormitoryFeeDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('缴纳宿舍费用')
        self.setGeometry(300, 300, 400, 250)
        self.payment = FeePayment()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 表单布局
        form_layout = QFormLayout()
        
        # 获取所有宿舍信息
        db = Database()
        db.connect()
        db.cursor.execute(
            "SELECT id, building, room_number FROM dormitory ORDER BY building, room_number"
        )
        dormitories = db.cursor.fetchall()
        db.close()
        
        # 宿舍选择下拉框
        self.dormitory_combo = QComboBox()
        for dorm in dormitories:
            self.dormitory_combo.addItem(f"{dorm[1]}-{dorm[2]} (ID: {dorm[0]})", dorm[0])
        form_layout.addRow('宿舍:', self.dormitory_combo)
        
        self.fee_type_input = QLineEdit()
        self.fee_type_input.setPlaceholderText('留空表示缴纳所有类型费用')
        form_layout.addRow('费用类型(可选):', self.fee_type_input)
        
        # 添加表单到主布局
        form_group = QGroupBox('宿舍缴费信息')
        form_group.setLayout(form_layout)
        layout.addWidget(form_group)
        
        # 按钮布局
        button_layout = QHBoxLayout()
        
        self.pay_button = QPushButton('缴费')
        self.pay_button.clicked.connect(self.pay_dormitory_fee)
        button_layout.addWidget(self.pay_button)
        
        self.cancel_button = QPushButton('取消')
        self.cancel_button.clicked.connect(self.reject)
        button_layout.addWidget(self.cancel_button)
        
        layout.addLayout(button_layout)
        self.setLayout(layout)
    
    def pay_dormitory_fee(self):
        dormitory_id = self.dormitory_combo.currentData()
        fee_type = self.fee_type_input.text().strip() or None
        
        try:
            if fee_type:
                result = self.payment.pay_dormitory_fees(dormitory_id, fee_type)
            else:
                result = self.payment.pay_dormitory_fees(dormitory_id)
            
            if result:
                QMessageBox.information(self, '成功', '宿舍费用已缴纳')
                self.accept()
        except Exception as e:
            QMessageBox.warning(self, '错误', f'缴费失败: {str(e)}')

# 费用查询窗口
class QueryFeeWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.query = FeeQuery()
        self.initUI()
        
    def initUI(self):
        layout = QVBoxLayout()
        
        # 查询选项
        option_group = QGroupBox('查询选项')
        option_layout = QVBoxLayout()
        
        self.query_all_btn = QRadioButton('查询所有费用记录')
        self.query_all_btn.setChecked(True)
        option_layout.addWidget(self.query_all_btn)
        
        self.query_by_dormitory_btn = QRadioButton('根据宿舍查询费用')
        option_layout.addWidget(self.query_by_dormitory_btn)
        
        self.query_by_status_btn = QRadioButton('根据缴费状态查询')
        option_layout.addWidget(self.query_by_status_btn)
        
        self.query_by_type_btn = QRadioButton('根据费用类型查询')
        option_layout.addWidget(self.query_by_type_btn)
        
        # 创建按钮组
        self.query_button_group = QButtonGroup()
        self.query_button_group.addButton(self.query_all_btn, 1)
        self.query_button_group.addButton(self.query_by_dormitory_btn, 2)
        self.query_button_group.addButton(self.query_by_status_btn, 3)
        self.query_button_group.addButton(self.query_by_type_btn, 4)
        
        option_group.setLayout(option_layout)
        layout.addWidget(option_group)
        
        # 查询参数表单
        self.param_group = QGroupBox('查询参数')
        self.param_layout = QFormLayout()
        
        self.dormitory_id_input = QLineEdit()
        self.dormitory_id_input.setPlaceholderText('例如: 1')
        self.param_layout.addRow('宿舍ID:', self.dormitory_id_input)
        
        self.status_combo = QComboBox()
        self.status_combo.addItem('未缴费', 'unpaid')
        self.status_combo.addItem('已缴费', 'paid')
        self.status_combo.addItem('已逾期', 'overdue')
        self.param_layout.addRow('缴费状态:', self.status_combo)
        
        self.fee_type_input = QLineEdit()
        self.fee_type_input.setPlaceholderText('例如: 水费、电费、住宿费')
        self.param_layout.addRow('费用类型:', self.fee_type_input)
        
        self.param_group.setLayout(self.param_layout)
        self.param_group.setVisible(False)
        layout.addWidget(self.param_group)
        
        # 查询按钮
        self.query_btn = QPushButton('查询')
        self.query_btn.clicked.connect(self.perform_query)
        layout.addWidget(self.query_btn)
        
        # 结果表格
        self.result_table = QTableWidget()
        self.result_table.setColumnCount(7)
        self.result_table.setHorizontalHeaderLabels(['费用ID', '宿舍', '费用类型', '金额', '生成日期', '截止日期', '状态'])
        self.result_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        layout.addWidget(self.result_table)
        
        # 连接信号
        self.query_button_group.buttonClicked.connect(self.on_query_option_changed)
        
        self.setLayout(layout)
    
    def on_query_option_changed(self, button):
        # 隐藏所有输入框
        for i in range(self.param_layout.rowCount()):
            self.param_layout.itemAt(i * 2 + 1).widget().setVisible(False)
            self.param_layout.itemAt(i * 2).widget().setVisible(False)
        
        # 根据选择的查询方式显示相应的输入框
        if button == self.query_by_dormitory_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(0).widget().setVisible(True)  # 宿舍标签
            self.param_layout.itemAt(1).widget().setVisible(True)  # 宿舍下拉框
        elif button == self.query_by_status_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(2).widget().setVisible(True)  # 状态标签
            self.param_layout.itemAt(3).widget().setVisible(True)  # 状态下拉框
        elif button == self.query_by_type_btn:
            self.param_group.setVisible(True)
            self.param_layout.itemAt(4).widget().setVisible(True)  # 费用类型标签
            self.param_layout.itemAt(5).widget().setVisible(True)  # 费用类型输入框
        else:
            self.param_group.setVisible(False)
    
    def perform_query(self):
        selected_option = self.query_button_group.checkedId()
        
        if selected_option == 1:  # 查询所有费用记录
            fees = self.query.query_all_fees()
            self.display_results(fees)
        
        elif selected_option == 2:  # 根据宿舍查询费用
            dormitory_id = self.dormitory_id_input.text().strip()
            
            if not dormitory_id:
                QMessageBox.warning(self, '警告', '宿舍ID不能为空')
                return
            
            try:
                dormitory_id = int(dormitory_id)
                fees = self.query.query_fees_by_dormitory(dormitory_id)
                
                if fees:
                    self.display_results(fees)
                else:
                    self.result_table.setRowCount(0)
                    QMessageBox.information(self, '提示', f'没有找到宿舍ID为 {dormitory_id} 的费用记录')
            except ValueError:
                QMessageBox.warning(self, '警告', '宿舍ID必须是数字')
        
        elif selected_option == 3:  # 根据缴费状态查询
            status = self.status_combo.currentData()
            fees = self.query.query_fees_by_status(status)
            
            if fees:
                self.display_results(fees)
            else:
                self.result_table.setRowCount(0)
                status_display = self.status_combo.currentText()
                QMessageBox.information(self, '提示', f'没有找到状态为 {status_display} 的费用记录')
        
        elif selected_option == 4:  # 根据费用类型查询
            fee_type = self.fee_type_input.text().strip()
            
            if not fee_type:
                QMessageBox.warning(self, '警告', '费用类型不能为空')
                return
            
            fees = self.query.query_fees_by_type(fee_type)
            
            if fees:
                self.display_results(fees)
            else:
                self.result_table.setRowCount(0)
                QMessageBox.information(self, '提示', f'没有找到类型为 {fee_type} 的费用记录')
    
    def display_results(self, fees):
        if not fees:
            self.result_table.setRowCount(0)
            QMessageBox.information(self, '提示', '没有找到任何费用记录')
            return
        
        self.result_table.setRowCount(len(fees))
        
        for row, fee in enumerate(fees):
            self.result_table.setItem(row, 0, QTableWidgetItem(str(fee[0])))
            self.result_table.setItem(row, 1, QTableWidgetItem(f"{fee[1]}-{fee[2]}"))
            self.result_table.setItem(row, 2, QTableWidgetItem(fee[3]))
            self.result_table.setItem(row, 3, QTableWidgetItem(str(fee[4])))
            self.result_table.setItem(row, 4, QTableWidgetItem(fee[5]))
            self.result_table.setItem(row, 5, QTableWidgetItem(fee[6]))
            
            status_display = "未缴费" if fee[7] == 'unpaid' else "已缴费" if fee[7] == 'paid' else "已逾期"
            self.result_table.setItem(row, 6, QTableWidgetItem(status_display))

# 宿舍费用管理主窗口
class FeeManagementWindow(QMainWindow):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle('宿舍费用管理')
        self.setGeometry(100, 100, 800, 600)
        self.initUI()
        
    def initUI(self):
        # 创建中央窗口部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建选项卡窗口
        tab_widget = QTabWidget()
        
        # 创建宿舍费用管理的各个功能选项卡
        self.generate_tab = QWidget()
        self.pay_tab = QWidget()
        self.query_tab = QueryFeeWidget()
        
        # 设置费用生成选项卡
        generate_layout = QVBoxLayout()
        generate_btn = QPushButton('生成费用账单')
        generate_btn.setMinimumHeight(50)
        generate_btn.setFont(QFont('Arial', 12))
        generate_btn.clicked.connect(self.open_generate_dialog)
        generate_layout.addWidget(generate_btn)
        
        batch_generate_btn = QPushButton('批量生成费用账单')
        batch_generate_btn.setMinimumHeight(50)
        batch_generate_btn.setFont(QFont('Arial', 12))
        batch_generate_btn.clicked.connect(self.open_batch_generate_dialog)
        generate_layout.addWidget(batch_generate_btn)
        
        generate_layout.addStretch()
        self.generate_tab.setLayout(generate_layout)
        
        # 设置费用缴纳选项卡
        pay_layout = QVBoxLayout()
        pay_btn = QPushButton('缴纳费用')
        pay_btn.setMinimumHeight(50)
        pay_btn.setFont(QFont('Arial', 12))
        pay_btn.clicked.connect(self.open_pay_dialog)
        pay_layout.addWidget(pay_btn)
        
        pay_dormitory_btn = QPushButton('缴纳宿舍费用')
        pay_dormitory_btn.setMinimumHeight(50)
        pay_dormitory_btn.setFont(QFont('Arial', 12))
        pay_dormitory_btn.clicked.connect(self.open_pay_dormitory_dialog)
        pay_layout.addWidget(pay_dormitory_btn)
        
        pay_layout.addStretch()
        self.pay_tab.setLayout(pay_layout)
        
        # 添加选项卡
        tab_widget.addTab(self.generate_tab, '费用生成')
        tab_widget.addTab(self.pay_tab, '费用缴纳')
        tab_widget.addTab(self.query_tab, '费用查询')
        
        main_layout.addWidget(tab_widget)
        
        # 返回按钮
        back_btn = QPushButton('返回主菜单')
        back_btn.clicked.connect(self.close)
        main_layout.addWidget(back_btn)
    
    def open_generate_dialog(self):
        dialog = GenerateFeeDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果生成成功，刷新查询选项卡的数据
            self.query_tab.perform_query()
    
    def open_batch_generate_dialog(self):
        dialog = BatchGenerateFeeDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果批量生成成功，刷新查询选项卡的数据
            self.query_tab.perform_query()
    
    def open_pay_dialog(self):
        dialog = PayFeeDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果缴费成功，刷新查询选项卡的数据
            self.query_tab.perform_query()
    
    def open_pay_dormitory_dialog(self):
        dialog = PayDormitoryFeeDialog(self)
        result = dialog.exec_()
        
        if result == QDialog.Accepted:
            # 如果宿舍缴费成功，刷新查询选项卡的数据
            self.query_tab.perform_query()

# 如果直接运行此文件，提供测试界面
if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = FeeManagementWindow()
    window.show()
    sys.exit(app.exec_())